﻿using System;
using System.Collections.Generic;
using System.Data.Linq;
using System.IO.IsolatedStorage;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AllenHung.FeedReader
{
    internal class MainModel : DataContext
    {
        #region Property to persist

        internal const int MAX_OPTION = 2;

        private bool SpeechOn = true;
        private bool Autoplay = true;
        private IsolatedStorageSettings settings;

        #endregion

        public MainModel(string connectionString) : base(connectionString)
        {
            if (!System.ComponentModel.DesignerProperties.IsInDesignTool)
            {
                settings = IsolatedStorageSettings.ApplicationSettings;
            }
        }

        private bool AddOrUpdateValue(string Key, Object value)
        {
            bool valueAdded = false;

            if (settings.Contains(Key))
            {
                settings[Key] = value;
            }
            else
            {
                settings.Add(Key, value);
                valueAdded = true;
            }
            return valueAdded;
        }

        private T GetValueOrDefault<T>(string Key, T defaultValue)
        {
            T value;

            // If the key exists, retrieve the value.
            if (settings.Contains(Key))
            {
                value = (T)settings[Key];
            }
            // Otherwise, use the default value.
            else
            {
                value = defaultValue;
            }
            return value;
        }

        internal object[] LoadFromIsolatedStorage()
        {
            object[] results = new object[MAX_OPTION];
            
            bool speechOn = GetValueOrDefault<bool>("SpeechOn", true);
            SpeechOn = speechOn;
            results[0] = speechOn;

            bool autoPlay = GetValueOrDefault<bool>("Autoplay", true);
            Autoplay = autoPlay;
            results[1] = autoPlay;
            return results;
        }

        internal void SaveToIsolatedStorage(object[] savedValues)
        {
            if (savedValues == null || savedValues.Length != MAX_OPTION)
            {
                return;
            }

            bool changed = false;

            
            if (SpeechOn != (bool)savedValues[0])
            {
                changed = true;
                SpeechOn = (bool)savedValues[0];
                AddOrUpdateValue("SpeechOn", SpeechOn);
            }
            if (Autoplay != (bool)savedValues[1])
            {
                changed = true;
                SpeechOn = (bool)savedValues[1];
                AddOrUpdateValue("Autoplay", Autoplay);
            }
            if (changed)
            {
                settings.Save();
            }
        }

        //Table of task items
        public Table<FeedSource> FeedSources;
    }
}
